package com.frank.pipeline.utils;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;

import java.io.Serializable;

public class ApiResponse<T> implements Serializable {

    private static final long serialVersionUID = 7563572234517927934L;

    private Status status;
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private T content;
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private String errorCode;
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private String errorMsg;
    private enum Status{
        ok,fail
    }

    public ApiResponse() { }

    public static <T> ApiResponse<T> success(T content){
        ApiResponse response = new ApiResponse();
        if (content != null){
            response.content = content;
        }
        response.status = Status.ok;
        return response;
    }

    public static ApiResponse<String> success() {
        return success("ok");
    }

    public static ApiResponse failed(String errorCode, String errorMsg){
        ApiResponse response = new ApiResponse();
        response.status = Status.fail;
        response.errorCode = errorCode;
        response.errorMsg = errorMsg;
        return response;
    }

    /**
     * failed with default <code>errorCode 101</code>
     * @param errorMsg
     * @return
     */
    public static ApiResponse failed(String errorMsg){
        return failed("101", errorMsg);
    }

    public Status getStatus() {
        return status;
    }
    public T getContent() {
        return content;
    }
    public String getErrorCode() {
        return errorCode;
    }
    public String getErrorMsg() {
        return errorMsg;
    }

    @JsonIgnore
    @JSONField(serialize = false)
    public boolean isFailed() {
        return Status.fail == status;
    }
    @JsonIgnore
    @JSONField(serialize = false)
    public boolean isOk() {
        return Status.ok == status;
    }

    public ApiResponse setContent(T content) {
        this.content = content;
        return this;
    }

}